<?php

require_once 'db.php';
require_once 'function.php';

$action = $_GET['action'];
switch ($action) {
    case 'add':
        $pid = $_POST['pid'];
        $category = $_POST['category'];
        categoryAdd($pid, $category);
        break;

    case 'update':
        $id = $_POST['id'];
        $pid = $_POST['pid'];
        $category = $_POST['category'];
        categoryUpdate($id, $pid, $category);
        break;

    case 'del':
        $id = (int)$_GET['id'];
        categoryDel($id);
        break;

    default:
        exit('非法操作');

}

function categoryAdd($pid, $category) {
    $conn = db::getInstance()->connect();

    $sql = "INSERT INTO `category` (`pid`, `category`) VALUES ({$pid}, '{$category}')"; //注意string类型要加单引号
    // echo $sql;exit;
    $res = $conn->query($sql);
    if ($res) {
        echo "<script>alert('添加分类成功');location.href='index.php';</script>";
        exit;
    } else {
        echo "<script>alert('添加分类失败');history.back(-1)</script>";
    }
}

function categoryDel($id) {
    $conn = db::getInstance()->connect();
    //查询当前分类下是否有子分类
    $sql = "SELECT count(*) AS `count` FROM `category` WHERE `pid` = '{$id}'";
    $res = $conn->query($sql);
    $result = $res->fetch_array();
    if ($result[0] > 0) {
        echo "<script>alert('请删除其子类后在删除');location.href='index.php';</script>";
        exit;
    } else {
        //删除操作
        $sql = "DELETE FROM `category` WHERE `id` = '{$id}'";
        $res = $conn->query($sql);
        if ($res) {
            echo "<script>alert('删除成功');location.href='index.php';</script>";
        }
    }
}

function categoryUpdate($id, $pid, $category) {
    $conn = db::getInstance()->connect();
    $sql = "UPDATE `category` SET `pid` = '{$pid}', `category` = '{$category}' WHERE `id` = '{$id}'";
    $res = $conn->query($sql);

    if ($res) {
        echo "<script>alert('修改成功');location.href='index.php';</script>";
    }
}